package run

import (
	"gitee.com/youbeiwuhuan/go-xxljob-executor/handler"
	"gitee.com/youbeiwuhuan/go-xxljob-executor/proccess"
	"sync"
)

const (
	DEFAULT_JOB_QUEUE_SIZE = 50
	MAX_IDLE_TIMES         = 30
)

const (
	TASK_STATUS_INQUEUE      = "in_queque"      // 等待执行
	TASK_STATUS_RUNNING      = "running"        // 执行中
	TASK_STATUS_RUN_COMPLETE = "run_complete"   // 执行完成
	TASK_STATUS_WAIT_RESULT  = "wait_result"    //等待异步结果
	TASK_STATUS_SEND_RESULT  = "sending_result" // 上报执行结果中
	TASK_STATUS_END          = "end"            // 结束
	TASK_STATUS_KILLED       = "killed"         // 被杀死

)

var (
	JobHandlerRepository sync.Map // bean name -> *IJobHandler
	JobRunnerRepository  sync.Map // jobId -> *JobRunner
)

func AddJobRunner(jobId int32, handler handler.IJobHandler, triggerCallback *proccess.TriggerCallbackProccessor) *JobRunner {
	jobRunner := NewJobRunner(jobId, handler, triggerCallback)
	jobRunner.Start()

	JobRunnerRepository.Store(jobId, jobRunner)

	return jobRunner

}

func GetJubRunner(jobId int32) *JobRunner {

	r, ok := JobRunnerRepository.Load(jobId)

	if ok {
		return r.(*JobRunner)
	}

	return nil

}
func RemoveJobRunner(jobId int32) *JobRunner {
	oldJobRunner := GetJubRunner(jobId)
	if nil != oldJobRunner {
		JobRunnerRepository.Delete(jobId)
		oldJobRunner.Stop()
		return oldJobRunner

	}

	return nil

}

func AddJobHandler(executorHandler string, handler handler.IJobHandler) {
	JobHandlerRepository.Store(executorHandler, handler)
}
func GetJobHandler(executorHandler string) handler.IJobHandler {
	r, ok := JobHandlerRepository.Load(executorHandler)

	if ok {
		return r.(handler.IJobHandler)
	}

	return nil
}

func RemoveJobHandler(executorHandler string) {
	JobHandlerRepository.Delete(executorHandler)
}
